<?php

	function clickable_link($text = '')
	{
		$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
		$ret = ' ' . $text;
		$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
		
		$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
		$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
		$ret = substr($ret, 1);
		return $ret;
	}

	function replaceLatex($text){
		
		$match = preg_match_all('(\$[^\$]*\$)',$text,$latexTextArray);
		//if there isnt latex in the text
		if ($match==0) return $text;
		
		
		$replacedText=$text;
		foreach ($latexTextArray[0] as &$latexText){
			//Remove the $ signs
			$result = substr($latexText,1);
			$result = substr($result,0,-1);
			
			//We replace the text for the latex img
			$replacedText = str_replace($latexText, "<img src=\"http://latex.codecogs.com/gif.latex?".$result."\" border=\"0\"/> ", $replacedText);
		
		}
		return $replacedText;
	}
	
	//Given a facebook user_id, returns the users name
	function getName($id) { 
		$resultTemp = mysql_query("SELECT * FROM users WHERE userid = '".$id."' LIMIT 1");
		
		return mysql_result($resultTemp, 0, 'name');
	} 

	include('dbchatcon.php');
	
	function showMoreMessagesButton($result)
	{
		if (mysql_num_rows($result) > 0)
		{
			echo "<p id='first_date' style='visibility: hidden'>".mysql_result($result, 0, 'date_created')."</p>";	
			
			// Check if there is more messages before the first I show
			$result2 = mysql_query("SELECT *, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM chatN_".$_REQUEST['chatTableName']." WHERE date_created < '".mysql_result($result, 0, 'date_created')."' ORDER BY date_created DESC LIMIT 1");
			if (mysql_num_rows($result2) > 0) {
			?>
				<div align="center" id="showMoreChatsBefore<? echo mysql_result($result, 0, 'date_created'); ?>" style="visibility: visible">
					<a id="showMoreChatsButton" style="float:center" onClick="loadMoreChatMessages();" > Ver mensajes anteriores </a> 
				</div> <?
			}
		}
	}
	
	if ($_REQUEST['getFirstsMessagges'] == 'false')
	{
		if ($_REQUEST['last_date'] == "-1")
		{
			$result = mysql_query("SELECT *, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM chatN_".$_REQUEST['chatTableName']." ORDER BY text_id DESC LIMIT 15");
			
			if (mysql_num_rows($result) > 0)
			{
				$first_date = mysql_result($result, mysql_num_rows($result) - 1, 'date_created');
				$result = mysql_query("SELECT *, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM chatN_".$_REQUEST['chatTableName']." WHERE date_created >= '".$first_date."' ORDER BY text_id ASC LIMIT 15");
				
				showMoreMessagesButton($result);
			}
		} else {
			$result = mysql_query("SELECT *, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM chatN_".$_REQUEST['chatTableName']." WHERE author_id != '".$_REQUEST['user_id']."' AND date_created > '".$_REQUEST['last_date']."' ORDER BY date_created ASC");
		}
	} else {
		$result = mysql_query("SELECT *, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM chatN_".$_REQUEST['chatTableName']." WHERE date_created < '".$_REQUEST['first_date']."' ORDER BY date_created DESC LIMIT 15");
		
		if (mysql_num_rows($result) > 0)
		{
			$last_date = mysql_result($result, mysql_num_rows($result) - 1, 'date_created');
			$result = mysql_query("SELECT *, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM chatN_".$_REQUEST['chatTableName']." WHERE date_created >= '".$last_date."' AND date_created < '".$_REQUEST['first_date']."' ORDER BY date_created ASC");
			
			showMoreMessagesButton($result);
		}
	}

	
	include('dbcon.php');	// For getting the users name

		for ($i = 0; $i < mysql_num_rows($result); $i++ )
		{
	   ?>
	   <div class="friends_area" id="record-<?php  echo mysql_result($result, $i, 'text_id')?>">
	 
	  
		   <label style="float:left" class="name">
			<b><?php $temp = explode(' ', getName(mysql_result($result, $i, 'author_id')));
					echo $temp[0] ?></b>
			
		   <?php  echo replaceLatex(clickable_link(mysql_result($result, $i, 'text_content')));?>
		   
		   <br clear="all" />

		   <span>
		   <?php  
		   
			// echo strtotime($row['date_created'],"Y-m-d H:i:s");
			
			$days = floor(mysql_result($result, $i, 'TimeSpent') / (60 * 60 * 24));
			$remainder = mysql_result($result, $i, 'TimeSpent') % (60 * 60 * 24);
			$hours = floor($remainder / (60 * 60));
			$remainder = $remainder % (60 * 60);
			$minutes = floor($remainder / 60);
			$seconds = $remainder % 60;
			
			if($days > 0)
				echo date('F d Y', mysql_result($result, $i, 'date_created'));
			elseif($days == 0 && $hours == 0 && $minutes == 0)
				echo "Hace algunos segundos.";		
			elseif($days == 0 && $hours == 0 && $minutes < 55)
				echo "Hace ".$minutes.' minutos';
			elseif($days == 0 && $hours < 2)
				echo "Hace aproximadamente una hora";
			elseif($days == 0)
				echo "Hace ".$hours." horas";
			else
				echo "fijate que hay cagada en chat.php";
			
		   ?>
		   
		   </span>

		   </label>
			<br clear="all" />
	   </div>
		<?php
		}
	?>
